package com.example.demo.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.demo.domain.ImgEntity;
import com.example.demo.domain.TextEntity;
import com.example.demo.loader.FontLoader;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ImageUtils {

    public static void main(String[] args) throws Exception {
        String path = "E:/Users/Desktop/项目/watermark.png";
        String str = "此件于原件一致，仅供测试使用，有效期至于2025-03-14，复印无效";
        ImgEntity img = new ImgEntity(str);
        img.setWidth(500);
        img.setHeight(360);
        img.setRotate(40);
        BufferedImage image = createTextWatermark(img);
        ImageIO.write(image, "PNG", new File(path));
    }

    public static BufferedImage readResource(String path) {
        try (InputStream is = ResourceUtil.getStreamSafe(path)) {
            return ImageIO.read(is);
        } catch (Exception ex) {
            return null;
        }
    }

    public static byte[] readResourceAsByteArray(String path) {
        return ResourceUtil.readBytes(path);
    }

    public static BufferedImage createTextWatermark(String text) {
        return createTextWatermark(new ImgEntity(text));
    }

    public static BufferedImage createTextWatermark(String text, int width, int height, float fontsize) {
        return createTextWatermark(new ImgEntity(text, width, height, fontsize));
    }

    public static BufferedImage createTextWatermark(ImgEntity img) {
        if (img == null || img.getText() == null) {
            throw new RuntimeException("img or text is null");
        }
        // 1.创建透明背景图片
        BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        // 2.设置抗锯齿和透明度
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, img.getOpacity()));
        // 3.设置字体
        Font font = FontLoader.loadFont(img.getFontsize());
        g2d.setFont(font);
        // 4.设置字体颜色和旋转角度
        g2d.setColor(img.getColor());
        g2d.translate(img.getWidth() / 2, img.getHeight() / 2);
        g2d.rotate(Math.toRadians(img.getRotate()));
        // 5.计算切分文字
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(img.getText());
        int textHeight = fontMetrics.getHeight();
        List<String> textList = splitText(img.getText(), textWidth, img.getWidth());
        // 6.绘制文字
        int y = - (textHeight * textList.size() / 2) ;
        for (String text : textList) {
            int lineWidth = fontMetrics.stringWidth(text);
            int x = - lineWidth / 2;
            g2d.drawString(text, x, y);
            y += textHeight * 2;
        }
        g2d.dispose();
        return image;
    }

    private static List<String> splitText(String originText, int textWidth, int imgWidth) {
        List<String> textList = new ArrayList<>();
        if (textWidth > imgWidth) {
            int len = imgWidth / (textWidth / originText.length()) - 2;
            // 切分文字
            while (!originText.isEmpty()) {
                if (originText.length() > len) {
                    textList.add(originText.substring(0, len));
                    originText = originText.substring(len);
                } else {
                    textList.add(originText);
                    originText = "";
                }
            }
        } else {
            textList.add(originText);
        }
        return textList;
    }

    /**
     * 需要调用方，手动关闭输入流
     * @param image 图片
     * @return 图片流
     */
    public static InputStream toInputStream(BufferedImage image) {
        return toInputStream(image, null);
    }

    /**
     * 图片转为byte数组
     * @param image 图片
     * @return 图片数组
     */
    public static byte[] toByteArray(BufferedImage image) {
        return toByteArray(image, null);
    }

    /**
     * 需要调用方，手动关闭输入流
     * @param image 图片
     * @param format 格式
     * @return 图片流
     */
    public static InputStream toInputStream(BufferedImage image, String format) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, format != null ? format : "PNG", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 图片转为byte数组
     * @param image 图片
     * @param format 格式
     * @return 图片数组
     */
    public static byte[] toByteArray(BufferedImage image, String format) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ImageIO.write(image, format != null ? format : "PNG", os);
            return os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
